<?php

declare(strict_types=1);
namespace App\Middleware;
/**
 * api认证中间件
 * 作者 刘传望
 * 宽松的token拦截，及时失败也往下进行，成功则获取user_id
 * Class TokenMiddleware
 * @package App\Middleware
 */

use Hyperf\Context\Context;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class TokenOptionalMiddleware implements MiddlewareInterface {

    protected ContainerInterface $container;

    protected RequestInterface $request;

    protected HttpResponse $response;
    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $url = $request->getUri()->getPath();

        $token = "";
        /*
         * 从header  Authorization 中取token
         * 这里做了两种逻辑，一个是走header里面取token,用于线上环境使用，另外新增了走传参获取，便于开发调试。
         */
        $header_authorization = $request->getHeader("Authorization");
        if($header_authorization && count($header_authorization) == 1){
            $header_authorization_string = $header_authorization[0];
            $header_authorization_data_arr = explode(" ",$header_authorization_string);
            if(count($header_authorization_data_arr) == 2){
                $token = $header_authorization_data_arr[1];
            }
        }
        if(isset($request->getQueryParams()['token'])){
            $token = $request->getQueryParams()['token'];
        }
        $tokenData = json_decode(base64_decode($token),true);
        print_r($tokenData);
        if($tokenData){
            Context::set("login_user_id",$tokenData['acl']['user_id']);
            Context::set("login_user_role",$tokenData['acl']['role']);
        }else{
            Context::set("login_user_id",0);
            Context::set("login_user_role",'');
        }
        return $handler->handle($request);
    }
}